# -*- coding: utf-8 -*-
import serial
import time

def cyclic_send(ser):
    numbers = [0, 1, 2, 3]  # 待发送数字序列
    duration_per_num = 5    # 每个数字发送时长（秒）
    send_interval = 0.5     # 发送间隔（秒）
    cycles = int(duration_per_num / send_interval)  # 每个数字发送次数
    
    while True:
        for current_num in numbers:
            start_time = time.time()
            print("正在发送数字: {}".format(current_num))
            
            # 持续发送当前数字
            for _ in range(cycles):
                try:
                    ser.write(str(current_num).encode('utf-8'))
                    time.sleep(send_interval)
                except KeyboardInterrupt:
                    return  # 允许通过Ctrl+C中断

try:
    ser = serial.Serial("/dev/ttyS0", 115200, timeout=1)
    if ser.isOpen():
        print("串口已打开: {}".format(ser.portstr))
        cyclic_send(ser)
    else:
        print("串口打开失败")
except serial.SerialException as e:
    print("串口异常: {}".format(str(e)))
except KeyboardInterrupt:
    ser.close()
    print("\n程序已终止")
finally:
    if 'ser' in locals() and ser.isOpen():
        ser.close()
